import tushare as ts 
import easyquotation
from easyquotation import helpers 
import util
import requests
import re
import time
import datetime
import akshare as ak

global stock_codes
ts.set_token('299a175cc58cbf70f1b7db307b65ab967c364e4fe215b6f7bf7391b4')
tushare_pro = ts.pro_api()
quotation_hk = easyquotation.use('hkquote') #数据接口选择，新浪 ['sina'] 腾讯 ['tencent', 'qq']
quotatio_timekl = easyquotation.use("timekline")
quotation_sina = easyquotation.use('sina') #数据接口选择，新浪 ['sina'] 腾讯 ['tencent', 'qq']


#转换数据[['id', 'name', 'yes_pri', 'now_pri', 'up_num', 'add_num']]
def convert_hk_data(data):
    res_arr = []
    for item in data:
        # 名称
        name = data[item]['name']
        # 今日开盘价
        yes_pri = data[item]["lastPrice"]
        # 现价 实时
        now_pri = data[item]["price"]
        # 涨跌幅度
        up_num = round(((float(now_pri) - float(yes_pri)) / float(yes_pri)), 4)*100
        # 涨跌幅度
        add_num = str(round(float(now_pri) - float(yes_pri), 3))
        res_arr.append({'id':item, 'name':name, 'yes_pri':yes_pri, 'now_pri':now_pri, 'up_num':up_num, 'add_num':add_num})
    return res_arr


#转换数据[['id', 'name', 'yes_pri', 'now_pri', 'up_num', 'add_num']]
def read_data_ag(data, ids):
    if not ids:
        return []
    res_arr = []
    for index in range(0, len(data["name"])):
        # 名称
        name = data["name"][index]
        # 今日开盘价
        yes_pri = data["pre_close"][index]
        # 现价 实时
        now_pri = data["price"][index]
        # 涨跌幅度
        up_num = round(((float(now_pri) - float(yes_pri)) / float(yes_pri)), 4)*100
        # 涨跌幅度
        add_num = str(round(float(now_pri) - float(yes_pri), 3))
        res_arr.append({'id':ids[index], 'name':name, 'yes_pri':yes_pri, 'now_pri':now_pri, 'up_num':up_num, 'add_num':add_num})
    return res_arr


#获取实时数据 H股
def real_hk(ids):
    news_hk = quotation_hk.real(ids) 
    return convert_hk_data(news_hk)

#获取实时数据 A股
def real_ag(ids):
    news = ts.get_realtime_quotes(ids) 
    return read_data_ag(news, ids)


#获取实时数据
def real_data(ids):
    ids_hk, ids_a = util.split_array_with_length(ids)
    res_array_hk = real_hk(ids_hk) 
    res_array_a = real_ag(ids_a)
    res_array_a.extend(res_array_hk)
    return res_array_a


def get_stock_codes(file):
    global stock_codes
    """获取所有股票 ID 到 all_stock_code 目录下"""
    try:
        response = requests.get("http://www.shdjt.com/js/lib/astock.js")
        with open(file,'w') as f:
            f.write(response.text)
            stock_codes = response.text.split('~')
    except:
        pass

# 查询日线
def get_daily_datas(code, start, end):
    return tushare_pro.daily(ts_code=code, start_date=start, end_date=end)


# 查询日线
def get_pro_bar(code, start, end, freq):
    return ts.pro_bar(ts_code=code, start_date=start, end_date=end,freq=freq)

# 获取股票类型
def get_stock_type(code):
    return helpers.get_stock_type(code)

def get_date(dateFormat, delta): 
    # 转换为可读模式
    return (datetime.date.today() + datetime.timedelta(days=delta)).strftime(dateFormat)

#获取时分数据
def get_hour_min(code, start, end):
    return ak.stock_zh_a_hist_min_em(symbol=code, start_date="{} 09:30:00".format(start), end_date="{} 15:00:00".format(end), period='1', adjust='')


    
